import os
import time
from datetime import datetime
from pathlib import Path


def is_empty_directory(dir_path):
    """
    判断目录是否为空目录

    Args:
        dir_path (str or Path): 目录路径

    Returns:
        bool: 如果是空目录返回True，否则返回False
    """
    try:
        # 使用os.listdir检查目录是否为空[1,6](@ref)
        if not os.listdir(dir_path):
            return True
        return False
    except (PermissionError, FileNotFoundError) as e:
        print(f"无法访问目录 {dir_path}: {e}")
        return False


def find_empty_directories(root_path):
    """
    递归查找指定目录下的所有空目录[1,5](@ref)

    Args:
        root_path (str or Path): 根目录路径

    Returns:
        list: 空目录路径列表
    """
    empty_dirs = []
    root_path = Path(root_path)

    if not root_path.exists() or not root_path.is_dir():
        print(f"错误：路径 {root_path} 不存在或不是目录")
        return empty_dirs

    # 使用os.walk遍历所有子目录[2](@ref)
    try:
        for current_dir, subdirs, files in os.walk(root_path):
            current_path = Path(current_dir)

            # 检查当前目录是否为空[6,8](@ref)
            if is_empty_directory(current_path):
                empty_dirs.append(current_path)

    except Exception as e:
        print(f"遍历目录时发生错误: {e}")

    return empty_dirs


def update_empty_directory_timestamp(dir_path, new_time=None):
    """
    更新空目录的时间戳

    Args:
        dir_path (Path): 目录路径
        new_time (float, optional): 新的时间戳，默认为当前时间

    Returns:
        bool: 成功返回True，失败返回False
    """
    if new_time is None:
        new_time = time.time()

    try:
        # 更新目录的访问时间和修改时间[3](@ref)
        os.utime(dir_path, (new_time, new_time))
        return True
    except Exception as e:
        print(f"更新目录 {dir_path} 时间戳失败: {e}")
        return False


def scan_and_update_empty_dirs(target_directory, use_time):
    """
    扫描并更新空目录的时间戳

    Args:
        target_directory (str): 目标目录路径
        use_time (number): 指定时间戳

    Returns:
        dict: 处理结果统计
    """
    print(f"开始扫描目录: {target_directory}")
    print("正在查找空目录..." + "\n" + "=" * 50)

    # 查找所有空目录[5](@ref)
    empty_directories = find_empty_directories(target_directory)

    if not empty_directories:
        print("未找到任何空目录")
        return {"total_found": 0, "successful_updates": 0, "failed_updates": 0}

    print(f"找到 {len(empty_directories)} 个空目录:")
    for i, dir_path in enumerate(empty_directories, 1):
        print(f"  {i}. {dir_path}")

    print("\n开始更新时间戳..." + "\n" + "-" * 30)

    # 确定要使用的时间戳
    # if use_current_time:
    #     new_timestamp = time.time()
    #     time_description = "当前时间"
    # else:
    #     # 使用找到的第一个空目录的原始时间（或其他逻辑）
    #     new_timestamp = os.path.getmtime(empty_directories[0])
    #     time_description = "原目录时间"
    new_timestamp = use_time

    human_time = datetime.fromtimestamp(new_timestamp).strftime("%Y-%m-%d %H:%M:%S")
    print(f"将空目录时间戳统一设置为: {human_time})")

    # 更新空目录的时间戳
    successful_updates = 0
    failed_updates = 0

    for dir_path in empty_directories:
        if update_empty_directory_timestamp(dir_path, new_timestamp):
            print(f"✓ 已更新: {dir_path}")
            successful_updates += 1
        else:
            print(f"✗ 更新失败: {dir_path}")
            failed_updates += 1

    # 输出统计结果
    print("\n" + "=" * 50)
    print("处理完成!")
    print(f"空目录总数: {len(empty_directories)}")
    print(f"成功更新: {successful_updates}")
    print(f"失败更新: {failed_updates}")

    return {
        "total_found": len(empty_directories),
        "successful_updates": successful_updates,
        "failed_updates": failed_updates,
        "empty_directories": empty_directories
    }


def main(target_dir, use_time):
    """主函数"""
    # 获取用户输入的目录路径
    # target_dir = input("请输入要扫描的目录路径（留空使用当前目录）: ").strip()

    if not target_dir:
        target_dir = "."

    # 验证目录是否存在[8](@ref)
    if not os.path.exists(target_dir):
        print(f"错误：目录 '{target_dir}' 不存在")
        return

    if not os.path.isdir(target_dir):
        print(f"错误：'{target_dir}' 不是目录")
        return

    # 询问用户要使用的时间戳类型
    # time_choice = input("请选择时间戳类型 (1-当前时间 / 2-保持原时间): ").strip()
    # use_current_time = (time_choice != "2")
    # use_time = os.path.getmtime(target_dir)
    # 执行扫描和更新
    scan_and_update_empty_dirs(target_dir, use_time)


# 高级版本：带日志记录和更多选项
def advanced_empty_dir_scanner(target_directory, use_current_time=True, log_file=None):
    """
    高级版本的空目录扫描和更新时间戳功能

    Args:
        target_directory (str): 目标目录
        use_current_time (bool): 是否使用当前时间
        log_file (str, optional): 日志文件路径

    Returns:
        dict: 详细的处理结果
    """
    start_time = time.time()
    results = {
        "start_time": datetime.now().isoformat(),
        "target_directory": target_directory,
        "empty_directories": [],
        "successful_updates": 0,
        "failed_updates": 0,
        "processing_time": 0
    }

    # 设置日志
    log_handle = None
    if log_file:
        log_handle = open(log_file, 'w', encoding='utf-8')
        log_handle.write(f"空目录时间戳更新日志 - {datetime.now()}\n")
        log_handle.write(f"目标目录: {target_directory}\n")
        log_handle.write("=" * 60 + "\n")

    def log_message(message):
        print(message)
        if log_handle:
            log_handle.write(message + "\n")

    try:
        # 扫描空目录
        empty_dirs = find_empty_directories(target_directory)
        results["empty_directories"] = [str(path) for path in empty_dirs]

        if not empty_dirs:
            log_message("未找到任何空目录")
            return results

        log_message(f"找到 {len(empty_dirs)} 个空目录")

        # 设置时间戳
        new_timestamp = time.time() if use_current_time else None

        # 更新每个空目录的时间戳
        for dir_path in empty_dirs:
            if new_timestamp is None:
                # 使用目录的原始时间
                dir_timestamp = os.path.getmtime(dir_path)
            else:
                dir_timestamp = new_timestamp

            if update_empty_directory_timestamp(dir_path, dir_timestamp):
                human_time = datetime.fromtimestamp(dir_timestamp).strftime("%Y-%m-%d %H:%M:%S")
                log_message(f"✓ 已更新: {dir_path} -> {human_time}")
                results["successful_updates"] += 1
            else:
                log_message(f"✗ 更新失败: {dir_path}")
                results["failed_updates"] += 1

    except Exception as e:
        error_msg = f"处理过程中发生错误: {e}"
        log_message(error_msg)
        results["error"] = str(e)

    finally:
        # 关闭日志文件
        if log_handle:
            end_time = time.time()
            results["processing_time"] = end_time - start_time

            log_handle.write("\n" + "=" * 60 + "\n")
            log_handle.write(f"处理完成时间: {datetime.now()}\n")
            log_handle.write(f"处理耗时: {results['processing_time']:.2f}秒\n")
            log_handle.write(f"找到空目录: {len(results['empty_directories'])}个\n")
            log_handle.write(f"成功更新: {results['successful_updates']}个\n")
            log_handle.write(f"失败更新: {results['failed_updates']}个\n")
            log_handle.close()

    return results


if __name__ == "__main__":
    # import config_setting
    import step_1_update_folder_last_modified
    # 简单使用

    target = r"D:\projects\kp-playnite"
    human_readable_time = "2025-2-22 19:30:30"

    time_format = "%Y-%m-%d %H:%M:%S"
    structured_time = time.strptime(human_readable_time, time_format)
    timestamp = time.mktime(structured_time)

    main(target, timestamp)
    step_1_update_folder_last_modified.main(target)
    # root = r"D:\projects"
    # dirs = os.listdir(root)
    # for target in dirs:
    #     if os.path.isdir(os.path.join(root, target)):
    #         main(os.path.join(root, target))

    # 高级使用示例（取消注释以下行来使用）
    # results = advanced_empty_dir_scanner(
    #     target_directory="./test_folder",
    #     use_current_time=True,
    #     log_file="./empty_dir_update.log"
    # )